<script setup>
import { ref, onMounted, nextTick } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { User, Lock } from "@element-plus/icons-vue";

// 表单数据
const loginData = ref({ username: "", password: "" });
const registerData = ref({ username: "", password: "", confirmPassword: "" });

// 引用
const loginFormRef = ref(null);
const registerFormRef = ref(null);
const isRegister = ref(false);
const loading = ref(false);

// 表单校验规则
const checkRePassword = (rule, value, callback) => {
  if (!value) callback(new Error("请再次确认密码"));
  else if (value !== registerData.value.password)
    callback(new Error("请确保两次输入的密码一致"));
  else callback();
};

const rules = {
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 5, max: 16, message: "用户名长度为5～16位", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 5, max: 16, message: "密码长度为5～16位", trigger: "blur" },
  ],
  confirmPassword: [{ validator: checkRePassword, trigger: "blur" }],
};

// 路由 & token
import { useTokenStore } from "@/stores/token.js";
import { userLoginService, userRegisterService } from "@/api/user";
import useUserInfoStore from "@/stores/userInfo";
const router = useRouter();
const tokenStore = useTokenStore();
const userInfoStore = useUserInfoStore();

// 登录
const login = async () => {
  if (loading.value) return;
  await loginFormRef.value.validate(async (valid) => {
    if (!valid) return;
    loading.value = true;
    try {
      const result = await userLoginService(loginData.value);
      console.log("登录响应:", result);
      if (result.code === 0) {
        // 清除旧的用户信息
        userInfoStore.removeInfo();
        // 设置新的token
        tokenStore.setToken(result.data.token);
        // 验证token
        const isValid = await tokenStore.validateToken();
        if (isValid) {
          ElMessage.success("登录成功");
          await router.push("/daily");
        } else {
          ElMessage.error("登录验证失败，请重试");
          tokenStore.removeToken();
        }
      } else {
        ElMessage.error(result.message || "登录失败");
      }
    } catch (err) {
      console.error("登录失败:", err);
      ElMessage.error("登录失败，请重试");
      tokenStore.removeToken();
    } finally {
      loading.value = false;
    }
  });
};

// 注册
const register = async () => {
  if (loading.value) return;
  await registerFormRef.value.validate(async (valid) => {
    if (!valid) return;
    loading.value = true;
    try {
      const result = await userRegisterService(registerData.value);
      console.log("注册响应:", result);
      if (result.code === 0) {
        ElMessage.success(result.message || "注册成功");
        if (result.data?.token) {
          // 清除旧的用户信息
          userInfoStore.removeInfo();
          // 设置新的token
          tokenStore.setToken(result.data.token);
          // 验证token
          const isValid = await tokenStore.validateToken();
          if (isValid) {
            await router.push("/daily");
          } else {
            ElMessage.error("登录验证失败，请重试");
            tokenStore.removeToken();
          }
        } else {
          isRegister.value = false;
          clear();
        }
      } else {
        ElMessage.error(result.message || "注册失败");
      }
    } catch (err) {
      console.error("注册失败:", err);
      ElMessage.error("注册失败，请重试");
      tokenStore.removeToken();
    } finally {
      loading.value = false;
    }
  });
};

// 清空数据并清除校验
const clear = async () => {
  loginData.value = { username: "", password: "" };
  registerData.value = { username: "", password: "", confirmPassword: "" };
  await nextTick(() => {
    loginFormRef.value?.clearValidate?.();
    registerFormRef.value?.clearValidate?.();
  });
};
</script>

<template>
  <div class="login-page">
    <!-- 背景图片 -->
    <img src="/image/background.webp" class="bg-image" />
    <!-- 登陆表单 -->
    <div class="form-container">
      <h1 class="form-title" v-if="!isRegister">登录</h1>
      <h1 class="form-title" v-else>注册</h1>
      <el-form
        v-if="!isRegister"
        ref="loginFormRef"
        size="large"
        autocomplete="off"
        :model="loginData"
        :rules="rules"
      >
        <el-form-item prop="username">
          <el-input
            v-model="loginData.username"
            :prefix-icon="User"
            placeholder="请输入用户名"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="loginData.password"
            :prefix-icon="Lock"
            type="password"
            placeholder="请输入密码"
          />
        </el-form-item>
        <el-form-item>
          <div class="flex">
            <el-checkbox>记住我</el-checkbox>
            <el-link type="primary" underline="never">忘记密码？</el-link>
          </div>
        </el-form-item>

        <el-form-item>
          <el-button class="button" type="primary" @click="login"
            >登录</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button
            link
            @click="
              isRegister = true;
              clear();
            "
            >没有账号？注册</el-button
          >
        </el-form-item>
      </el-form>

      <el-form
        v-else
        ref="registerFormRef"
        size="large"
        autocomplete="off"
        :model="registerData"
        :rules="rules"
      >
        <el-form-item prop="username">
          <el-input
            v-model="registerData.username"
            :prefix-icon="User"
            placeholder="请输入用户名"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="registerData.password"
            type="password"
            placeholder="请输入密码"
          />
        </el-form-item>
        <el-form-item prop="confirmPassword">
          <el-input
            v-model="registerData.confirmPassword"
            type="password"
            placeholder="请确认密码"
          />
        </el-form-item>
        <el-form-item>
          <el-button class="button" type="primary" @click="register"
            >注册</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button
            link
            @click="
              isRegister = false;
              clear();
            "
            >已有账号？登录</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<style>
/* 全局样式：移除滚动条和默认边距 */
html,
body {
  margin: 0;
  padding: 0;
  /* overflow: hidden; */ /* 隐藏所有滚动条 */
  width: 100%;
  height: 100%;
}
</style>

<style lang="scss" scoped>
.login-page {
  position: relative;
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  background: #000; /* 可以保留一个备用背景色 */
}

.bg-image {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  object-fit: cover; /* 铺满且裁剪溢出部分 */
  z-index: 0;
}

/* 表单样式 */
.form-container {
  position: absolute;
  top: 50%;
  right: 10%; /* 移动到右边10% */
  transform: translateY(-50%); /* 垂直居中 */
  background: rgba(255, 255, 255, 0.7); /* 调整透明度 */
  padding: 50px 40px; /* 增加内边距 */
  border-radius: 16px;
  box-shadow: 0px 8px 30px rgba(0, 0, 0, 0.2); /* 更强、更柔和的阴影 */
  width: 400px; /* 稍微宽一点 */
  max-width: calc(100% - 40px); /* 确保在小屏幕上响应 */
  text-align: center;
  backdrop-filter: blur(10px); /* 磨砂玻璃效果 */
  -webkit-backdrop-filter: blur(10px); /* Safari兼容 */
  border: 1px solid rgba(255, 255, 255, 0.3); /* 细微边框 */

  .form-title {
    font-size: 28px; /* 稍微大一点 */
    font-weight: bold;
    margin-bottom: 30px; /* 更多空间 */
    color: #222;
  }

  .el-form-item {
    margin-bottom: 25px; /* 更多间距 */
  }

  .button {
    width: 100%;
    height: 48px; /* 更高一点 */
    font-size: 16px; /* 更大的字体 */
    border-radius: 8px; /* 更圆润的按钮 */
  }

  .flex {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%; /* 确保占据全部宽度 */
    margin-bottom: 15px; /* 添加一些底部间距 */
  }

  .el-link {
    margin-left: 0 !important; /* 移除硬编码 margin */
  }
}

/* 响应式布局 */
@media screen and (max-width: 768px) {
  .form-container {
    width: 90%;
    max-width: 360px;
    padding: 30px 20px; /* 调整移动端内边距 */
    right: auto; /* 移除右边距设置 */
    /* left 和 transform 已经在主样式中设置，此处无需重复 */
  }

  .form-title {
    font-size: 24px;
    margin-bottom: 20px;
  }

  .el-form-item {
    margin-bottom: 20px;
  }

  .button {
    height: 44px;
  }

  .flex {
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
  }

  .el-link {
    margin-left: 0 !important;
  }
}
</style>
